// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/core/plan_node.h>
#include <pollux/parse/plan_nodeId_generator.h>

#include <duckdb.hpp> // @manual

namespace kumo::pollux::core {
    /// Hook to allow plugging different connectors for table scan to
    /// DuckDbQueryPlanner.
    using MakeTableScan = std::function<PlanNodePtr(
        const std::string &id,
        const std::string &name,
        const RowTypePtr &rowType,
        const std::vector<std::string> &columnNames)>;

    class DuckDbQueryPlanner {
    public:
        DuckDbQueryPlanner(memory::MemoryPool *pool) : pool_{pool} {
        }

        void registerTable(
            const std::string &name,
            const std::vector<RowVectorPtr> &data);

        void registerTable(const std::string &name, const RowTypePtr &type);

        void registerScalarFunction(
            const std::string &name,
            const std::vector<TypePtr> &argTypes,
            const TypePtr &returnType);

        // TODO Allow replacing built-in DuckDB functions. Currently, replacing "sum"
        // causes a crash (a bug in DuckDB). Replacing existing functions is useful
        // when signatures don't match.
        void registerAggregateFunction(
            const std::string &name,
            const std::vector<TypePtr> &argTypes,
            const TypePtr &returnType);

        void registerTableScan(MakeTableScan func) {
            makeTableScan_ = std::move(func);
        }

        PlanNodePtr plan(const std::string &sql);

    private:
        ::duckdb::DuckDB db_;
        ::duckdb::Connection conn_{db_};
        memory::MemoryPool *pool_;
        melon::F14FastMap<std::string, std::vector<RowVectorPtr> > tables_;
        MakeTableScan makeTableScan_{nullptr};
    };

    PlanNodePtr parseQuery(
        const std::string &sql,
        memory::MemoryPool *pool,
        const melon::F14FastMap<std::string, std::vector<RowVectorPtr> > &
                inMemoryTables = {});
} // namespace kumo::pollux::core
